import {useCallback, useContext, useEffect, useRef, useState} from "react";
import { getAllTypesOfMetasByPageCode} from "@/biz-components/claim-items/components";
import {DetailContext} from "@/biz-components/claim-items/components/DetailContext";
import {xhrPostJson} from "@/services";
import {minus, plus} from "@ey-utils/utils/numberPrecision";
import {
	CommonFilter,
	CommonFilterItem,
	CellInput,
	FilterFunctions,
	CommonTable
} from "@/biz-components/claim-items/components-v2";
import * as CommonDataSource from '../../../common-data-source';
import {useField} from "@formily/react";
import {Field} from "@formily/core/lib/models";
import ClaimItemsDataUtil from "@/biz-components/claim-items/ClaimItemsDataUtil";
/**
 * @author DongPing
 * 2022/1/12 15:39
 *
 * 收款池-业务认领-未清项 认领明细
 *
 * */

// 子模型编码
const PAGE_CODE = 'ClaimInfoB_IT_L';

export function CollectionBusinessNotClean(props: {
	value: any[],
	onChange: (value: any[]) => void,

	// 收款明细事项，首款池-业务认领的时候 查询未清项数据
	collectionDetailItemType: string,
	// 认领对象
	claimTarget: string,
	// 认领门店
	shop: string,
	// 匹配类型
	matchType: string,
	// 收款类型
	collectionType: string
}) {
	const {value = [], onChange, collectionDetailItemType = '', claimTarget = '',shop = '', matchType, collectionType} = props;
	const [tableColumnMetas, setTableColumnMetas] = useState<any[]>([]);
	useEffect(function () {
		getAllTypesOfMetasByPageCode(PAGE_CODE).then((result) => {
			setTableColumnMetas(result.tableColumnMetas);
		})
	}, []);

	const detailMode = useContext(DetailContext);

	const lastDataRef = useRef<any[]>([]);

	const previousRequestPromiseRef = useRef<Promise<any>>(null);
	const filterFunctionRef = useRef<(data: any[]) => any[]>(null);
	function onFilterChange() {
		if(filterFunctionRef.current) {
			props.onChange(filterFunctionRef.current(lastDataRef.current || []));
		}
	}

	useEffect(function () {
		if(detailMode) return;
		let params: any = {
			cllctDetail: collectionDetailItemType,
			cllctType: collectionType,
			companyCode: shop,
			matchNatur: matchType,
			claimObject: claimTarget
		};
		let currentPromise = xhrPostJson('/asm/claimDetail/remainCllctList', params);
			// .then((res: any) => {
			// 	res.result = [{remainAmt: 33, shkzg: 'S'}, {remainAmt: 34, shkzg: 'H'}]
			// 	return res;
			// })
		if(previousRequestPromiseRef.current) {
			previousRequestPromiseRef.current.finally(() => {
				currentPromise.then((res: any) => {
					const d = ClaimItemsDataUtil.setTempId(res.result || []);
					lastDataRef.current = d;
					onChange(d);
				});
			})

		} else {
			currentPromise.then((res: any) => {
				const d = ClaimItemsDataUtil.setTempId(res.result || []);
				lastDataRef.current = d;
				onChange(d);
			});
		}
		// @ts-ignore
		previousRequestPromiseRef.current = currentPromise;
		// 查询认领明细数据
	}, [collectionDetailItemType, collectionType, shop, matchType, claimTarget]);

	const queryProfitOptions = useCallback((p: CellInput.AsyncPageSelectSearchParam) => {
		// return CommonDataSource.others.queryProfitCenterPage(p, props.shop);
	}, [props.shop]);

	const validateTableDataRef = useRef<() => boolean>(null);

	const field = useField<Field>();
	useEffect(function () {
		field.setValidator(() => {
			if(!value.some((item) => item.__checked)) {
				return {type: 'error', message: '请选择认领明细'}
			}
			if(validateTableDataRef.current && !validateTableDataRef.current()) {
				return {type: 'error', message: '认领明细填写有误'}
			} else {
				return null;
			}
		});
		return function () {
			field.setValidator(() => true);
		}
	}, [value]);

	return (
		<div>

			{
				detailMode ? null :
					<CommonFilter filterFunctionRef={filterFunctionRef} onChange={onFilterChange} metaArr={tableColumnMetas}>
						<CommonFilterItem name={'postDate'} Component={[CellInput.SelectDateRange, {}]} filterFunction={FilterFunctions.dateRangeMatch}/>
						<CommonFilterItem<string, CellInput.AsyncPageSelectExtraProps> name={'profitCenter'} Component={[CellInput.AsyncPageSelect, {search: queryProfitOptions}]} filterFunction={FilterFunctions.stringEqual}/>
						{/*{*/}
						{/*	matchType === 'Supplier' ?*/}
						{/*		<CommonFilterItem<string, CellInput.AsyncPageSelectExtraProps> name={'zzcoals'} Component={[CellInput.AsyncPageSelect, {search: CommonDataSource.others.queryAssistantOptionsPage}]} filterFunction={FilterFunctions.stringEqual}/>*/}
						{/*		:*/}
						{/*		null*/}
						{/*}*/}
						<CommonFilterItem name={'remainAmt'} Component={[CellInput.NumberInput, {}]} filterFunction={FilterFunctions.numberEqual}/>

					</CommonFilter>
			}

			<CommonTable
				pageCode={PAGE_CODE}
				metaArr={tableColumnMetas}
				value={value}
				onChange={onChange}
				detailMode={detailMode}
				claimItemsInvalid={true}
				validateFunctionRef={validateTableDataRef}
				checkOperation
				onCheckChange={(r: object | null, checked) => {
					for(const item of value) {
						if(r === null || r === item) {
							item.__checked = checked;
							item.thisClaimAmt = checked ? item.remainAmt : ''
						}
					}
					onChange([...value]);
				}}
				columnsOptionArr={[
					{
						name: 'thisClaimAmt',
						component: [CellInput.NumberInput, {}],
						validator: (v, r) => {
							if(!r.__checked) return true;
							let nv = Number(v);
							let remainAmt = Number(r.remainAmt);
							return (nv > 0) && (nv <= remainAmt)
						}
					}
				]}
			/>
		</div>


	)
}

CollectionBusinessNotClean.calculateAmount = calculateAmount;

/**
 * 计算金额汇总
 * 本次明细认领金额汇总等于勾选的未清项：S借项金额-H贷项金额
 * */
function calculateAmount(data: any[]): number {
	let result = 0;

	for(const row of data) {
		if(row.__checked) {
			// 借贷标识
			let tag = row['shkzg'];
			let isLend = tag === 'S';
			let isLoan = tag === 'H';
			// 金额
			let amount = Number(row.thisClaimAmt);
			if(isNaN(amount)) continue;
			if(isLend) {
				result = plus(result, amount);
			} else if(isLoan) {
				result = minus(result, amount);
			}
		}
	}

	return result;
}

CollectionBusinessNotClean.getCheckedRecords = function (data: any[] = []) {
	return ClaimItemsDataUtil.removeTempId(data.filter((item) => !!item.__checked))
}
